package com.gsit.ocrbatch.services;

import static com.gsit.ocrbatch.utils.FileConstant.FILE_PATH_SEPARATOR;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gsit.ocrbatch.domain.Record;
import com.gsit.ocrbatch.domain.WebConfig;
import com.gsit.ocrbatch.utils.FileConstant.FileFlow;

@Repository
public class OcrFileWriter {
	
	@Autowired
	private WebConfig webConfig;
	
	public void write(List<Record> records,final FileFlow fileFlow)throws IOException{
		
		for (Record record : records) {
			write(webConfig.getApacheFilePath()+FILE_PATH_SEPARATOR+fileFlow.getInFolder().getPath()+FILE_PATH_SEPARATOR+record.getName(),
					webConfig.getApacheFilePath()+FILE_PATH_SEPARATOR+fileFlow.getOutFolder().getPath()+FILE_PATH_SEPARATOR+record.getName());
			
		}
		
	}
	
	public void write(String sourcePath, String targetPath)throws IOException{
		write(new File(sourcePath), new File(targetPath));
		
	}
	
	
	public void writeFolderToFolder(File sourceFolder, String targetFolderPath)throws IOException{
		
		if(sourceFolder == null) return;
		
		if(sourceFolder.isDirectory() ){
			for (File sourceFile : sourceFolder.listFiles()) {
				File targerFile = new File(targetFolderPath+FILE_PATH_SEPARATOR+sourceFile.getName());
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>");
				write(sourceFile, targerFile);
			}
		}	
		
	}
	
	public void write(File source, File target)throws IOException{
		if(target.isFile()){
			target.delete();
		}
		target.setExecutable(true);
		copyFile(source, target);
		
		if(source.isFile()){
			source.delete();
		}
	}
	
	
	private static void copyFile(File source, File target) {
	    try (InputStream fis = new FileInputStream(source);
	        OutputStream fos = new FileOutputStream(target)){
	 
	        byte[] buf = new byte[8192];
	 
	        int i;
	        while ((i = fis.read(buf)) != -1) {
	            fos.write(buf, 0, i);
	        }
	    }
	    catch (Exception e) {
	        e.printStackTrace();
	    }
	}

}
